package com.wmlive.hhvideo.common.ossutils;

import android.text.TextUtils;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.ObjectMetadata;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.wmlive.hhvideo.application.DCApplication;
import com.wmlive.hhvideo.common.base.BasePresenter;
import com.wmlive.hhvideo.common.base.BaseView;
import com.wmlive.hhvideo.common.network.HttpConstant;
import com.wmlive.hhvideo.heihei.beans.opus.OpusPublishRequestBean;
import com.wmlive.hhvideo.heihei.beans.opus.OpusPubllicResponseBean;
import com.wmlive.hhvideo.heihei.beans.oss.OSSTokenResponse;
import com.wmlive.hhvideo.heihei.beans.splash.InitCatchData;
import com.wmlive.networklib.entity.DCNetObserver;

/**
 *
 * Created by kangzhen on 2017/6/6.
 */

public class UploadPresenter extends BasePresenter<BaseView> {

    private UpLoadInterface mUpLoadInterface;//上传回调接口
    private String strUploadPath;//本地存储位置

    public UploadPresenter(BaseView view) {
        super(view);
    }

    /**
     * 设置回传接口
     * @param mUpLoadInterface
     */
    public void setmUpLoadInterface(UpLoadInterface mUpLoadInterface) {
        this.mUpLoadInterface = mUpLoadInterface;
    }

    /**
     * 设置本地文件
     * @param strUploadPath
     */
    public void setStrUploadPath(String strUploadPath) {
        this.strUploadPath = strUploadPath;
    }

    /**
     * 获取ossToken 并且上传服务器
     * * @param module  (message，avatar，opus)
     * @param format
     * message’: [‘png’, ‘mp3’, ‘jpg’, ‘mp4’]，
     * ’avatar’: [‘png’, ‘jpg’] ‘
     * opus’: [‘mp4’, ‘jpg’, ‘webp’, ‘jpeg’]
     */
    public void getOSSTokenAndUploadInfo(String module,final String format){
        if(!TextUtils.isEmpty(module) && !TextUtils.isEmpty(format)){
            executeRequest(HttpConstant.TYPE_OSSTOKEN_TOKEN_CODE, getHttpApi().getOssToken(InitCatchData.sysOssToken(), module, format))
                    .subscribe(new DCNetObserver<OSSTokenResponse>(){
                        @Override
                        public void onRequestDataReady(int requestCode, String message, OSSTokenResponse response) {
                            //上传阿里云
                            if(response!=null && !TextUtils.isEmpty(strUploadPath)){
                                actionUploadALiBaBa(response,format);
                            }else{
                                if(mUpLoadInterface!=null){
                                    UploadALiResultBean mBean = new UploadALiResultBean();
                                    mBean.setUpload_type(UploadALiResultBean.TYPE_UPLOAD_OSSTOKEN);
                                    mBean.setErrormsg(message);
                                    mBean.setErrorcode(HttpConstant.TYPE_OSSTOKEN_UPLOAD_ERROR_CODE);
                                    mBean.setmOssTokenResult(null);
                                    mUpLoadInterface.onFailsUpload(mBean);
                                }
                            }
                        }

                        @Override
                        public void onRequestDataError(int requestCode, int serverCode, String message) {
                            if(mUpLoadInterface!=null){
                                UploadALiResultBean mBean = new UploadALiResultBean();
                                mBean.setUpload_type(UploadALiResultBean.TYPE_UPLOAD_OSSTOKEN);
                                mBean.setErrormsg(message);
                                mBean.setErrorcode(serverCode);
                                mBean.setmOssTokenResult(null);
                                mUpLoadInterface.onFailsUpload(mBean);
                            }
                        }
                    });
        }
    }
    /**
     * 上传阿里云
     */
    private void actionUploadALiBaBa(final OSSTokenResponse ossTokenResult,String format) {
        String endpoint = ossTokenResult.getFileInfo().getEndpoint();
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(ossTokenResult.getCredentials().getAccessKeyId(), ossTokenResult.getCredentials().getAccessKeySecret(), ossTokenResult.getCredentials().getSecurityToken());

        OSS oss = new OSSClient(DCApplication.getDCApp(), endpoint, credentialProvider);
        // 构造上传请求
        PutObjectRequest put = new PutObjectRequest(ossTokenResult.getFileInfo().getBucketName(), ossTokenResult.getFileInfo().getPath(), strUploadPath);
        String strContentType = OSSUtils.getOssContentTypeByFormat(format);
        if(!TextUtils.isEmpty(strContentType)){
                ObjectMetadata metadata = new ObjectMetadata();
                metadata.setContentType(strContentType); // 设置content-type
                put.setMetadata(metadata);
            }

        // 异步上传时可以设置进度回调
        put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
            @Override
            public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                if(null!=mUpLoadInterface) {
                    mUpLoadInterface.onProgress(request, currentSize, totalSize);
                }

            }
        });
        OSSAsyncTask task = oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                if(null!=mUpLoadInterface) {
                    UploadALiResultBean mBean = new UploadALiResultBean();
                    mBean.setUpload_type(UploadALiResultBean.TYPE_UPLOAD_ALIBABA);
                    mBean.setmOSSRequest(request);
                    mBean.setmOSSResult(result);
                    mBean.setmOssTokenResult(ossTokenResult);
                    mUpLoadInterface.onSuccessUpload(mBean);
                }
            }

            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常
                if(null!=mUpLoadInterface){
                    UploadALiResultBean mBean = new UploadALiResultBean();
                    mBean.setUpload_type(UploadALiResultBean.TYPE_UPLOAD_ALIBABA);
                    mBean.setmOSSRequest(request);
                    mBean.setmClientException(clientExcepion);
                    mBean.setmServiceException(serviceException);
                    mUpLoadInterface.onFailsUpload(mBean);
                }
            }
        });
        // task.waitUntilFinished();
        // task.cancel(); // 可以取消任务
        //task.waitUntilFinished(); // 可以等待任务完成
    }
    /**
     * 上传作品信息
     * @param bean
     */
    public void submintOpusInfo(OpusPublishRequestBean bean){
        if(bean!=null){
            executeRequest(HttpConstant.TYPE_OPUS_UPLOAD_CODE, getHttpApi().uploadOpusInfo(InitCatchData.opusSaveOpus(), bean.getTitle(),bean.getOpus_path(),bean.getOpus_file_sign(),bean.getOpus_cover(),bean.getOpus_cover_sign(),bean.getOpus_gif_cover(),bean.getOpus_gif_cover_sign(),String.valueOf(bean.getTopic_id()),String.valueOf(bean.getMusic_id()),bean.getAt_user_ids(),Integer.getInteger(String.valueOf(bean.getOpus_length()))))
                    .subscribe(new DCNetObserver<OpusPubllicResponseBean>(){
                        @Override
                        public void onRequestDataReady(int requestCode, String message, OpusPubllicResponseBean response) {
                            //上传作品成功
                            if(mUpLoadInterface!=null) {
                                UploadALiResultBean mBean = new UploadALiResultBean();
                                mBean.setUpload_type(UploadALiResultBean.TYPE_UPLOAD_BUSSINESS);
                                mUpLoadInterface.onSuccessUpload(mBean);
                            }
                        }

                        @Override
                        public void onRequestDataError(int requestCode, int serverCode, String message) {
                            //上传作品失败
                            if(mUpLoadInterface!=null){
                                UploadALiResultBean mBean = new UploadALiResultBean();
                                mBean.setUpload_type(UploadALiResultBean.TYPE_UPLOAD_BUSSINESS);
                                mUpLoadInterface.onFailsUpload(mBean);
                            }

                        }
                    });
        }
    }
}
